//
//  DeviceListViewController.m
//  AlinkDemo
//
//  Created by Vincent on 2017/10/26.
//  Copyright © 2017年 aliyun. All rights reserved.
//

#import "DeviceListViewController.h"
#import "DeviceTableViewCell.h"
#import "Constant.h"
#import "DeviceTabBarController.h"
#import <MJRefresh.h>
#import <AlinkSDK/AlinkAccount.h>
#import "CallViewController.h"
#import "AppDelegate.h"
@interface DeviceListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentedContol;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *datas;

@end
static NSString *const cellId = @"DeviceList";
@implementation DeviceListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.isEyesOpen = YES;


    self.view.backgroundColor = UIColorFromRGB(0xeaf3f2);
    self.tableView.backgroundColor = [UIColor clearColor];
    
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [YKBusinessFramework equesGetDeviceList];
    }];
    
    self.segmentedContol.layer.cornerRadius = self.segmentedContol.frame.size.height/2.0f;
    self.segmentedContol.layer.borderColor = UIColorFromRGB(0x02C7B2).CGColor;
    self.segmentedContol.layer.borderWidth = 1.f;
    self.segmentedContol.clipsToBounds = YES;

//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出" style:UIBarButtonItemStyleDone target:self action:@selector(logout)];
    
    //隐藏返回键
    self.navigationItem.hidesBackButton = YES;
    
    NSDictionary *session =  [[AlinkAccount sharedInstance] currentSession];
    NSString *userName = session[@"ak_account"];
    if (userName) {
        [YKBusinessFramework equesSdkLoginWithUrl:SERVERADDRESS username:userName appKey:APPKEY];
    }
    

    [self.tableView registerNib:[UINib nibWithNibName:@"DeviceTableViewCell" bundle:nil] forCellReuseIdentifier:cellId];
    [self.tableView setTableFooterView:[UIView new]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageResult:) name:equesOnMessageResultNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showCallView:) name:@"ShowCallViewNotificaion" object:nil];
    
    //添加门锁跳转segment
    [self.segmentedContol addTarget:self action:@selector(toBone:) forControlEvents:UIControlEventValueChanged];
//    [self changestatusBarView];
    
}
-(void)changestatusBarView{
    UIView *statusBarView = [[UIView alloc]   initWithFrame:CGRectMake(0, -20,    self.view.bounds.size.width, 20)];
    statusBarView.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar addSubview:statusBarView];
    //清除导航栏下划线
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

/*************toBone跳转start****************/
-(void)toBone:(UISegmentedControl *)seg{
    switch (seg.selectedSegmentIndex) {
        case 0:
            [self goToBone];
            break;
            
        default:
            break;
    }
    
}
-(void)goToBone{
    [self.navigationController popViewControllerAnimated:NO];
}
/*************toBone跳转end****************/
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [YKBusinessFramework equesGetDeviceList];

}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)setTableFooterView{
    
    
    if (self.datas.count>0) {
        [self.tableView setTableFooterView:[UIView new]];
        
    }else{
        UIImageView *footerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH)];
        footerView.contentMode = UIViewContentModeScaleAspectFit;
       
        footerView.image = [UIImage imageNamed:@"device_empty"];
            
        [self.tableView setTableFooterView:footerView];
        
    }
    
}



- (void)logout{

//    [YKBusinessFramework equesLogout];
    [self.navigationController popViewControllerAnimated:YES];
}


-(void)showCallView:(NSNotification *)notification{


    NSString *from = notification.object;
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    CallViewController *vc = [sb instantiateViewControllerWithIdentifier:@"Call"];
    vc.bid = from;
    vc.isDoolCall = YES;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:vc animated:NO completion:^(void){

    }];

}


#pragma mark 收到的消息
- (void)onMessageResult:(NSNotification *)notification{
    NSDictionary *messageResult = [notification object];

    NSString *method = messageResult[@"method"];

    if ([method isEqualToString:@"getok"]) {
        [YKBusinessFramework equesGetDeviceList];

    }else if ([method isEqualToString:@"bdylist"]) {
        
        [self.tableView.mj_header endRefreshing];
        NSArray *bdylist = [messageResult objectForKey:@"bdylist"];
        NSArray *onlines = [messageResult objectForKey:@"onlines"];

        [self.datas removeAllObjects];
        for (NSDictionary *bdy in bdylist) {
            NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithDictionary:bdy];
            for (NSDictionary *onlineBdy in onlines) {
                if ([bdy[@"bid"] isEqualToString:onlineBdy[@"bid"]]) {
                    [data addEntriesFromDictionary:onlineBdy];
                    break;
                }

            }
            [self.datas addObject:data];

        }
        [self setTableFooterView];

        [[NSUserDefaults standardUserDefaults] setObject:self.datas forKey:@"DeviceList"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdateTitleNotification" object:nil];
        [self.tableView reloadData];
    } 
    NSLog(@"收到的消息:%@",messageResult);
    //    [self analysisMessage:messageResult];
    //    _placeHolderLabel.text = @"";
    //    _QRcodeImageView.image = nil;
    //    _onMessageResultTextView.text = [NSString stringWithFormat:@"%@",messageResult];
}


#pragma mark - TableView 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datas.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    DeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];

    NSDictionary *data = self.datas[indexPath.row];
    [cell setData:data];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *data = self.datas[indexPath.row];

    [self performSegueWithIdentifier:@"DeviceTabBar" sender:data];
}



#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

    if ([segue.identifier isEqualToString:@"DeviceTabBar"]) {
        DeviceTabBarController *vc =[segue destinationViewController];
        NSDictionary *dict = sender;
        vc.deviceDict = dict;
    }
}

- (NSMutableArray *)datas{
    if (!_datas) {
        _datas = [[NSMutableArray alloc] init];
    }

    return _datas;
}

@end
